const db = require('../tools/mongodb');
const config = require('./mongodb.config');
const delay =require('../tools/delay');
const format  =require('../tools/format')();

const comments = config.jd.comments;
const replies = config.jd.replies;
const videos = config.jd.videos;
const images = config.jd.images;
const delArray = [comments,replies,videos,images];
const log = config.jd.log;

//保留数据规则
let rule = {
    week:1
};


let del = async ()=>{
    let block = new Date();
    {
        if(rule.year)
        block.setFullYear(block.getFullYear()-rule.year);
        if(rule.month)
        block.setMonth(block.getMonth()-rule.month);
        if(rule.week)
        block.setDate(block.getDate() - rule.week*7);
        if(rule.date)
        block.setDate(block.getDate() - rule.date);
    }
    let block_str = block.format('yyyy-MM-dd');
    let startTime = new Date();
    let logger = {operation:"delete",
        logId:Number(startTime),
        context:{},
        start:startTime.format('yyyy-MM-dd HH:mm:ss')
    };
    for(let collection of delArray){
        if(collection.collection == 'comments'){
            await db.deleteMany(collection,{create:{'$lt':block_str}}).then(result=>{
                logger.context[collection.collection] = result;
            }).catch(error=>{
                logger.context[collection.collection] = error;
            });
        }
        else{
            await db.deleteMany(collection,{}).then(result=>{
                logger.context[collection.collection] = result;
            }).catch(error=>{
                logger.context[collection.collection] = error;
            });
        }
    }
    logger.end = new Date().format('yyyy-MM-dd HH:mm:ss');
    await db.insertOne(log,logger);
    console.log(logger,'删除完成');
}

module.exports = del;